<template>
	<div id="MyCollect" class="mycollect">
		<Segment :items="segments" @itemClick="barClick"></Segment>
		<div class="content">
			<ul id="collectionView" ref="collectionView">
				<!-- 我的收藏 -->
				<li class="mcli" v-if="type == '1'" v-for="(item,index) in products" v-bind:style="getCellStyle(index)">
					<a href="javascript:void(0)" @click="lookBtnClick(item.product.id)">
						<div class="img_back" >
							<img :src=" item.product ? item.product.thumUrl:''" :width="cellWidth" :height="cellWidth/133 * 177" />
							<div class="update_chapters" v-bind:style="{'width':cellWidth-1}">阅读至:{{item.lastLookChapterVo == undefined ? "":item.lastLookChapterVo.name}}</div>
							
						</div>

						<span class="productName">{{ item.product ? item.product.name:""}}</span>
						<button v-if="isEdit" class="delete" v-on:click="deleteBtnClick(item)"></button>
					</a>
				</li>
				<!-- 浏览记录 -->
				<li class="mcli" v-if="type == '2'" v-for="(item,index) in products" v-bind:style="getCellStyle(index)">
					<a href="javascript:void(0)" @click="lookBtnClick(item.productVo.id)">
						<div class="img_back">
							<img :src="item.productVo.thumUrl" :width="cellWidth" :height="cellWidth/133 * 177" />
							<div class="update_chapters" v-bind:style="{'width':cellWidth-1}"><div>浏览至:{{item.lastLookChapterVo == undefined ? "":item.lastLookChapterVo.name}}</div></div>
						</div>
						
						<span class="productName">{{item.productVo.name}}</span>
						<button v-if="isEdit" class="delete" v-on:click="deleteBtnClick(item)"></button>
					</a>
				</li>
			</ul>
			<div class="no_data" v-if="products.length == 0"><span>{{noDataText}}</span></div>
			<Page v-bind:info="paginationVo" v-on:btnsclick="pageBtnClick" style="border-top: 1px solid #cdcdcd;padding: 5px 0px;"></Page>
		</div>
	</div>
</template>

<script>
	import UserInfoManager from "../../js/UserInfoManager.js"
	import HttpUtil from "../../js/HttpUtil.js"
	import SLMUtil from "../../js/SLMUtil.js"
	import Page from '../pages/Page.vue'
	import Segment from '../pages/Segment.vue'

	export default {
		components: {
			Page,
			Segment
		},
		data() {
			return {
				segments: [{'title':"浏览记录"},{'title':"我的收藏"}],
				isEdit: false,
				products: [],
				cellWidth: '180px',
				cellNum: 1,
				paginationVo: {
					"pageSize": 20,
					"pageNo": 1,
					"firstResult": 0,
					"nextPage": 0,
					"prePage": 0,
					"totalCount": 0,
					"totalPage": 0,
					"firstPage": true,
					"lastPage": true
				},
				rootPath: SLMUtil.getRootPath(),
				type: '2', //1:代表收藏，2代表浏览记录
				noDataText: '没有数据',
			}
		},
		mounted() {
			//console.log("加载我的收藏mounted")
			let that = this;
			this.updateCellWidth();
			window.onresize = () => {
				return (() => {
					that.updateCellWidth();
				})()
			}
			this.requestData()
			//console.log("加载我的收藏mounted--end")
		},
		beforeRouteLeave(to, from, next) {
			console.log("离开路由停止监听")
			window.onresize = null
			//离开路由停止监听
			window.removeEventListener('scroll', this.handleScroll, true);
			next();
		},
		methods: {
			barClick:function (index) {
				var nowType = this.type
				if (index == 0) {//点击第一个，浏览记录
					nowType = "2"
				}else if(index == 1) {// 点击我的收藏
					nowType = "1"
				}
				
				console.log("home点击："+index)
				if (this.type != nowType) {
					this.type = nowType
					this.requestData()
				}
			},
			requestData:function() {
				// let type = SLMUtil.getUrlVariable("type")
				// this.type = type
				if (this.type == '1') { // 请求收藏列表
					this.requestCollectData();
				} else if (this.type == '2') { // 请求浏览列表
					this.requestBrowseData();
				}
			},
			requestCollectData: function() {
				let that = this;

				this.noDataText = "暂无收藏"

				let sessionKey = UserInfoManager.getInfo().userExt.sessionKey
				var params = new URLSearchParams();

				params.append('pageNumber', this.paginationVo.pageNo);
				params.append('pageSize', this.paginationVo.pageSize);
				let url = "collections/productList.do"
				params.append('sessionKey', sessionKey);

				console.log("请求收藏数据:" + url + "参数：" + params)
				HttpUtil.post(url, params)
					.then(response => {
						console.log(JSON.stringify(response.data));

						if (response.data.code == 0) {
							var data = response.data.data
							if (typeof(data) == "string") {
								data = JSON.parse(data)
								console.log("转JSON后：" + JSON.stringify(data));
							}
							that.products = data.list
							that.paginationVo = data.paginationVo;
							console.log("得到的翻页信息" + that.paginationVo);
							that.$nextTick(() => {
								
								
								that.refreshParentHeight(parent)
								console.log("DOM 更新了收藏UI");
								that.updateCellWidth();
							})
						}
					})
					.catch(function(error) {
						console.log(error);
					});
			},
			requestBrowseData: function() {
				let that = this;
				this.noDataText = "暂无浏览"

				let sessionKey = UserInfoManager.getInfo().userExt.sessionKey
				var params = new URLSearchParams();

				params.append('pageNumber', this.paginationVo.pageNo);
				params.append('pageSize', this.paginationVo.pageSize);
				let url = "click/list.do"
				params.append('sessionkey', sessionKey);

				console.log("请求浏览数据:" + url + "参数：" + params)
				HttpUtil.post(url, params)
					.then(response => {
						console.log("浏览记录数据："+JSON.stringify(response.data));

						if (response.data.code == 0) {
							var data = response.data.data

							that.products = data
							that.paginationVo = response.data.paginationVo;
							console.log("得到的翻页信息" + that.paginationVo);
							that.$nextTick(() => {
								console.log("DOM 更新了,让父frame刷新高度+++++++");
								that.refreshParentHeight(parent)
								that.updateCellWidth();
							})
						}
					})
					.catch(function(error) {
						console.log(error);
					});
			},
			deleteBtnClick: function(item) {
				let that = this;
				let type = SLMUtil.getUrlVariable("type")
				this.type = type
				this.noDataText = type == '1' ? "暂无收藏" : "暂无浏览"

				let sessionKey = UserInfoManager.getInfo().userExt.sessionKey
				var params = new URLSearchParams();


				let url = ''
				if (type == '1') { //收藏
					url = "collections/delete.do"
					params.append('sessionKey', sessionKey);
					params.append('productId', item.product.id);

				} else if (type == '2') { //浏览记录
					url = "click/productDelete.do"
					params.append('sessionkey', sessionKey);
					params.append('recorderId', item.id);
				}

				console.log("请求数据:" + url + "参数：" + params)
				HttpUtil.post(url, params)
					.then(response => {
						console.log(JSON.stringify(response.data));

						if (response.data.code == 0) {
							if (that.type == '1') {
								that.requestCollectData();
							} else if (that.type == '2') {
								that.requestBrowseData();
							}
						} else {
							alert(response.data.message)
						}
					})
					.catch(function(error) {
						console.log(error);
						alert("删除失败，网络出错")
					});
			},
			lookBtnClick: function(id) {
				if (this.isEdit) {
					return;
				}
				// let url = this.rootPath + '/product/detail?productId=' + id
				// window.open(url)

				this.$router.push({
					path: '/WorkDetail',
					query: {
						productId: id
					}
				})
			},
			pageBtnClick: function(index) {
				if (index == -1) { //上一页
					this.paginationVo.pageNo = this.paginationVo.pageNo - 1;
					this.requestData();
				} else if (index == -2) { //下一页
					console.log("点击，下一页");
					this.paginationVo.pageNo = this.paginationVo.pageNo + 1;
					this.requestData();
				}
			},
			editBtnClick: function(isEdit) {
				this.isEdit = isEdit;
				try {
					//父frame刷新高度
					this.$nextTick(() => {
						console.log("DOM 更新了,让父frame刷新高度+++++++");
						that.refreshParentHeight(parent)

					})
				} catch (error) {
					console.log("warn:刷新父frame失败")
				}
			},
			updateCellWidth: function() { //更新所有cell宽度
				let array = this.getCellFineWidth(10)
				if (array) {
					let width = array[0]
					let num = array[1]

					this.cellWidth = width
					this.cellNum = num

					console.log('每行个数:' + num + "cell宽度:" + width)
					let that = this
					this.$nextTick(() => {
						console.log("DOM 更新了,让父frame刷新高度+++++++");
						that.refreshParentHeight(parent)
					})
				}
			},
			refreshParentHeight: function(parent) {
				// if (parent) {
				// 	parent.refreshIframesHeight();
				// }
			},
			getCellFineWidth: function(num) { //获取cell最适合宽度
				if (this.$refs.collectionView == undefined) {
					return
				}
				let allwidth = this.$refs.collectionView.clientWidth // $("#collectionView").width()
				console.log("获取到collection宽度" + allwidth)
				if (typeof(allwidth) == "undefined") {
					console.log('总宽度未定义啊')
					return;
				}
				console.log('总宽度:' + allwidth)
				if (!allwidth) {
					return null;
				}
				let padding = 10 //间距
				let cellW = (allwidth - padding * (num - 1)) / num
				if (cellW >= 133) {
					return [cellW, num]
				} else {
					return this.getCellFineWidth(num - 1)
				}
			},
			getCellStyle: function(index) {
				console.log('这是第一个:index:' + index + '余数:' + (index % this.cellNum))
				if (index % this.cellNum == 0) { //每行 第一个
					return {
						width: this.cellWidth + 'px'
					}
				} else {
					return {
						width: this.cellWidth + 'px',
						'margin-left': '10px'
					}
				}
			}
		}

	}
</script>

<style scoped>
	@import "../../css/MyCollect.css";
</style>
